package com.example.translateappjava.Service.ChatGPT;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
/**
 * @author gu
 * 这里是调用ChatGpt的实现类
 */
public class ChatGPTImplication implements ChatGPTInterface.ChatClient{
private static final String API_URL = "https://api.chatanywhere.tech/v1/chat/completions";
private static final String AUTH_TOKEN = "Bearer sk-616q0WL7AeJnpspnAgFR7VHX6ltYvAejwIvyjuXZzQRttO1b";

    // 建议添加JSON转义方法，避免特殊字符导致的问题
    private String escapeJson(String input) {
        if (input == null) return "";
        return input
                .replace("\\", "\\\\")
                .replace("\"", "\\\"")
                .replace("\b", "\\b")
                .replace("\f", "\\f")
                .replace("\n", "\\n")
                .replace("\r", "\\r")
                .replace("\t", "\\t");
    }


/**
* @param message 输入给ChatGPt的内容
*/
    @Override
    public String getChatResponse(String message) throws IOException {
        URL url = new URL(API_URL);
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        conn.setRequestMethod("POST");
        conn.setRequestProperty("Content-Type", "application/json");
        conn.setRequestProperty("Authorization", AUTH_TOKEN);
        conn.setDoOutput(true);

        String systemContent = "你是青鸾，一个智能医疗助手，无所不知，负责回答用户给你的问题，不要输出markdown语法，纯文本输出";
        String jsonInputString = "{\"model\": \"deepseek-v3\",\"messages\": [" +
                "{\"role\": \"system\",\"content\": \"" + escapeJson(systemContent) + "\"}," +
                "{\"role\": \"user\",\"content\": \"" + escapeJson(message) + "\"}" +
                "]}";


        try (OutputStream os = conn.getOutputStream()) {
            byte[] input = jsonInputString.getBytes("utf-8");
            os.write(input, 0, input.length);
        }

        int responseCode = conn.getResponseCode();
        if (responseCode == HttpURLConnection.HTTP_OK) {
            StringBuilder response;
            try (BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream(),"UTF-8"))) {
                String line;
                response = new StringBuilder();
                while ((line = in.readLine()) != null) {
                    response.append(line);
                }
            }
            return response.toString();
        } else {
            throw new IOException("POST request failed: HTTP error code : " + responseCode);
        }
    }
}
